app.push(function(){
    var Mail = function(){
        var mail = false;
        var mode = 'in';
        var getDataMode = 'get';
        this.init = function(url){
            url = app.cloneArray(url || app.currentUrl);
            if(url[1] == 'in' || url[1] == 'out'){
                url[2] = url[1]+"";
                url[1] = 'list';
            }
            if(this[url[1]])this[url[1]](url);
            else this.showData(url[1]);
        }
        this.showData = function(id){
            mlhAPI.mail.get(
            {
                id: id,
                callback: function(data){
                    app.main.unmask();
                    if(data['result'] == 'success'){
                        var data = data.data.element;
                        data['mode'] = mode;
                        $.tmpl( 'mail_content', data).prependTo(app.elements.general_content.html(''));
                    }
                }
            })
        }
        this.add = function(url){
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            var user_id = url[2]*1||false;
            if(isNaN(user_id) || !user_id){
                this.build();
                app.leftMenu.setMessagesLeftMenu();
                app.main.unmask();
            }else{
                mlhAPI.user.get({
                    id:user_id,
                    callback: function(data){
                        console.log(data);
                        this_.build({
                            user_id:data.data.info.user_id,
                            to:data.data.info.name
                        });
                        app.leftMenu.setMessagesLeftMenu();
                        app.main.unmask();
                    }
                })
            }
            
        }
        this.build = function(data){
            jQuery.extend(data, {
                editMode: mail!=false
            });
            var el = $.tmpl('create_mail',data);
            el.prependTo(app.elements.general_content.html(''));
            el.find('#to').autocomplete({
                source: "api.php?v=toList&c=mail",
                minLength: 2,
                select: function( event, ui ) {
                    el.find('[name=user_id]').val(ui.item ? ui.item.id :0);
                }
            });
            app.decorate.validateRule($('#mailEditForm input, #mailEditForm textarea'),
            {
                success: ' ',
                endValid: function(error){
                    if(!error){
                        $('#mailEditForm .control-group').each(function(){
                            if($(this).hasClass('error')) error = true;
                            $(this).find('*[rel=req]').each(function(){
                                var value = $(this).val();
                                if(!value) error = true;
                            });
                        });
                    }
                    $('#mailEditForm button[type=submit]').attr('class', !error ? 'btn btn-success' : 'btn btn-warning');
                    if(!error){
                       $('#mailEditForm').find('.alert-info').show();
                       $('#mailEditForm').find('.alert[data-type=error]').hide();
                    }
                }
            });

            $('#mailEditForm form').submit(function(){
                if($('#mailEditForm button[type=submit]').hasClass('btn-warning')){
                    $('#mailEditForm').find('.alert[data-type=error]').addClass('alert-error').text("Заполните все необходимые поля").show();
                    $('#mailEditForm').find('.alert-info').hide();
                    $('#mailEditForm').find('*[rel=req]').each(function(){
                        var value = $(this).val();
                        if(!value) {
                            $(this).parents('.control-group:first')
                                .attr('class','row control-group warning span12 no_left_margin')
                                .find('.alert:first').text('Это поле обязательно надо заполнить').show();
                            
                        }
                    });
                    return false;
                }
                var formData = {
                    callback: function(data){
                        console.log(data);
                        if(data.data['errors'] || data.data['error']){
                            var text = "";
                            if(data.data['errors']){
                                for(var k in data.data.errors){
                                    if(k=='email')$('#mailEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                                    text += "<div>" + data.data.errors[k] +"</div>";
                                }
                            }else{
                                text += "<div>" + data.data['error'] +"</div>";
                            }
                            $('#mailEditForm').find('.alert[data-type=error]').addClass('alert-error').html(text).show();
                            $('#mailEditForm').find('.alert-info').hide();
                            $('#mailEditForm button[type=submit]').attr('class', 'btn btn-warning');
                        }else{
                            $('#mailEditForm').find('.alert[data-type=error]').hide();
                            $('#mailEditForm button[type=submit]').attr('class', 'btn btn-success');
                            app.static.success({description:'Ваше сообщение было отправлено'})
                            getDataMode = 'get_rc';
                            app.go('#mail/list/out');
                        }
                    }
                }
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                formData['model'] = 'mail';
                console.log(formData);
                mlhAPI.mail.set(formData);
                return false;
            });
        }
        this.list = function(url){
            var mailContainer = false;
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            if(url[2] == 'in' || url[2] == 'out') mode = url[2];
            app.topMenu.breadcrumbList[1] = ['Список сообщений','#mail/list/in'];
            app.topMenu.breadcrumbList[2] = [(mode == 'out' ? "Исходящие" : "Входящие"),'#mail/list/'+mode];
            app.topMenu.buildBreadcrumb();
            app.leftMenu.setMessagesLeftMenu();
            
            var el = $.tmpl('manage_mail_list',{
                mode: mode
            });
            mailContainer = $(el).find('[rel=mail_list]:first');
            el.prependTo(app.elements.general_content.html(''));
            mlhAPI.mail.getList({
                mode: mode,
                requestType: getDataMode,
                callback: function(data){
                    console.log(data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    mailContainer.html(data.data.length ? '' : 'Нет сообщений');
                    for(var i in data.data){
                        var info = data.data[i];
                        info['mode'] = mode;
                        var el = $.tmpl('manage_mail_element', info);
                        el.prependTo(mailContainer);
                        app.decorate.setEvents(el);
                    }
                }
            });
            getDataMode = 'get';
        }
    }
    app['mail'] = new Mail();
});